<?php
namespace app\controller;

/**
 * 网站控制器 - 处理网站生成相关功能
 */
class WebsiteController
{
    /**
     * 首页 - 网站生成器界面
     */
    public function index()
    {
        // 获取所有可用的组件
        $components = $this->getAvailableComponents();
        
        View::assign('components', $components);
        return View::fetch('website/index');
    }
    
    /**
     * 生成网站
     */
    public function generate()
    {
        if (Request::isPost()) {
            // 获取用户选择的组件
            $selectedComponents = Request::post('components', []);
            
            // 生成网站HTML
            $html = $this->buildWebsite($selectedComponents);
            
            // 保存生成的网站
            $fileName = $this->saveGeneratedWebsite($html);
            
            return json([
                'code' => 0,
                'message' => '网站生成成功',
                'data' => [
                    'fileName' => $fileName,
                    'previewUrl' => '/preview/' . $fileName
                ]
            ]);
        }
        
        return $this->index();
    }
    
    /**
     * AI生成组件数据
     */
    public function aiGenerateComponent()
    {
        if (Request::isPost()) {
            $componentType = Request::post('type', '');
            $params = Request::post('params', []);
            
            if (empty($componentType)) {
                return json([
                    'code' => 1,
                    'message' => '组件类型不能为空'
                ]);
            }
            
            // 调用AI生成组件数据
            $componentData = ai_generate_component_data($componentType, $params);
            
            return json([
                'code' => 0,
                'message' => 'AI生成组件数据成功',
                'data' => $componentData
            ]);
        }
    }
    
    /**
     * 预览生成的网站
     */
    public function preview($fileName)
    {
        $filePath = APP_PATH . '../../generated_sites/' . $fileName;
        
        if (file_exists($filePath)) {
            header('Content-Type: text/html; charset=utf-8');
            readfile($filePath);
            exit;
        }
        
        return '文件不存在';
    }
    
    /**
     * 获取所有可用的组件
     */
    private function getAvailableComponents()
    {
        $componentsDir = APP_PATH . '../../template/datas/components/';
        $components = [];
        
        if (is_dir($componentsDir)) {
            $files = scandir($componentsDir);
            
            foreach ($files as $file) {
                if ($file === '.' || $file === '..') continue;
                
                if (pathinfo($file, PATHINFO_EXTENSION) === 'json') {
                    $componentType = pathinfo($file, PATHINFO_FILENAME);
                    $components[] = [
                        'type' => $componentType,
                        'name' => get_component_title($componentType),
                        'file' => $file
                    ];
                }
            }
        }
        
        return $components;
    }
    
    /**
     * 构建网站HTML
     */
    private function buildWebsite($selectedComponents)
    {
        // 读取页面配置
        $pageConfig = $this->getPageConfig();
        
        // 开始构建HTML
        $html = '<!DOCTYPE html>';
        $html .= '<html lang="zh-CN">';
        $html .= '<head>';
        $html .= '<meta charset="UTF-8">';
        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
        $html .= '<title>' . $pageConfig['name'] . '</title>';
        
        // 引入外部资源
        $html .= $this->getExternalResources();
        
        // 添加页面样式
        $html .= $this->getPageStyles($pageConfig['settings']);
        
        $html .= '</head>';
        $html .= '<body>';
        
        // 循环加载选中的组件
        foreach ($selectedComponents as $componentType) {
            $html .= $this->renderComponent($componentType, $pageConfig['settings']);
        }
        
        // 添加JavaScript
        $html .= $this->getJavaScriptCode();
        
        $html .= '</body>';
        $html .= '</html>';
        
        return $html;
    }
    
    /**
     * 获取页面配置
     */
    private function getPageConfig()
    {
        $configPath = APP_PATH . '../../template/datas/index.json';
        
        if (file_exists($configPath)) {
            $json = file_get_contents($configPath);
            return json_decode($json, true);
        }
        
        // 默认配置
        return [
            'name' => '智能生成网站',
            'settings' => [
                'theme' => [
                    'primaryColor' => '#165DFF',
                    'secondaryColor' => '#36CFC9',
                    'accentColor' => '#722ED1',
                    'textColor' => '#1D2129',
                    'lightColor' => '#F2F3F5'
                ],
                'layout' => [
                    'containerWidth' => '1200px',
                    'sectionPadding' => '60px 0'
                ]
            ]
        ];
    }
    
    /**
     * 获取外部资源链接
     */
    private function getExternalResources()
    {
        $resources = '';
        $resources .= '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">';
        $resources .= '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">';
        $resources .= '<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>';
        $resources .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>';
        
        return $resources;
    }
    
    /**
     * 获取页面样式
     */
    private function getPageStyles($settings)
    {
        $theme = $settings['theme'];
        $layout = $settings['layout'];
        
        $styles = '<style>';
        $styles .= ':root {';
        $styles .= '--primary-color: ' . $theme['primaryColor'] . ';';
        $styles .= '--secondary-color: ' . $theme['secondaryColor'] . ';';
        $styles .= '--accent-color: ' . $theme['accentColor'] . ';';
        $styles .= '--text-color: ' . $theme['textColor'] . ';';
        $styles .= '--light-color: ' . $theme['lightColor'] . ';';
        $styles .= '}';
        $styles .= '</style>';
        
        return $styles;
    }
    
    /**
     * 渲染组件
     */
    private function renderComponent($componentType, $settings)
    {
        // 获取组件数据
        $componentData = get_component_data($componentType, $componentType . '.json');
        
        // 根据组件类型渲染不同的模板
        $componentTemplate = $this->getComponentTemplate($componentType);
        
        // 渲染组件HTML
        return $this->renderComponentTemplate($componentTemplate, $componentData, $settings);
    }
    
    /**
     * 获取组件模板
     */
    private function getComponentTemplate($componentType)
    {
        // 在实际项目中，应该从视图文件或数据库中获取模板
        // 这里为了简化，使用硬编码的模板
        $templates = [
            'navbar' => $this->getNavbarTemplate(),
            'hero' => $this->getHeroTemplate(),
            'services' => $this->getServicesTemplate(),
            'footer' => $this->getFooterTemplate()
            // 可以添加更多组件模板
        ];
        
        return isset($templates[$componentType]) ? $templates[$componentType] : '';
    }
    
    /**
     * 渲染组件模板
     */
    private function renderComponentTemplate($template, $data, $settings)
    {
        // 这里是一个简单的模板渲染实现
        // 在实际项目中，应该使用更强大的模板引擎
        $result = $template;
        
        // 替换模板中的变量
        $result = str_replace('{{component.name}}', $data['name'] ?? '', $result);
        $result = str_replace('{{theme.primaryColor}}', $settings['theme']['primaryColor'] ?? '', $result);
        $result = str_replace('{{theme.secondaryColor}}', $settings['theme']['secondaryColor'] ?? '', $result);
        
        // 可以添加更多的替换逻辑
        
        return $result;
    }
    
    /**
     * 获取导航栏模板
     */
    private function getNavbarTemplate()
    {
        return '<nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm fixed-top">
            <div class="container">
                <a class="navbar-brand" href="#">{{component.name}}</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav ml-auto">
                        <li class="nav-item active">
                            <a class="nav-link" href="#">首页</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#services">服务</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#about">关于我们</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#contact">联系我们</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>';
    }
    
    /**
     * 获取英雄区域模板
     */
    private function getHeroTemplate()
    {
        return '<section class="hero" style="background-color: {{theme.primaryColor}}; color: white; padding: 100px 0;">
            <div class="container text-center">
                <h1 class="display-4 mb-4">{{component.name}}</h1>
                <p class="lead mb-6">欢迎使用智能网站生成器，快速创建您的企业网站</p>
                <a href="#services" class="btn btn-light btn-lg">了解更多</a>
            </div>
        </section>';
    }
    
    /**
     * 获取服务模块模板
     */
    private function getServicesTemplate()
    {
        return '<section id="services" class="py-12 bg-light">
            <div class="container">
                <div class="text-center mb-10">
                    <h2 class="display-4">{{component.name}}</h2>
                </div>
                <div class="row">
                    <div class="col-md-4 mb-6">
                        <div class="card h-100">
                            <div class="card-body">
                                <i class="fa fa-laptop fa-3x mb-4" style="color: {{theme.primaryColor}};"></i>
                                <h3 class="card-title">网站建设</h3>
                                <p class="card-text">专业的网站设计与开发，为您的企业打造专属网络形象</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-6">
                        <div class="card h-100">
                            <div class="card-body">
                                <i class="fa fa-mobile fa-3x mb-4" style="color: {{theme.primaryColor}};"></i>
                                <h3 class="card-title">移动应用</h3>
                                <p class="card-text">响应式设计，确保您的网站在各种设备上都能完美展示</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-6">
                        <div class="card h-100">
                            <div class="card-body">
                                <i class="fa fa-search fa-3x mb-4" style="color: {{theme.primaryColor}};"></i>
                                <h3 class="card-title">SEO优化</h3>
                                <p class="card-text">专业的搜索引擎优化，提高您网站的搜索排名和曝光率</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>';
    }
    
    /**
     * 获取页脚模板
     */
    private function getFooterTemplate()
    {
        return '<footer class="bg-dark text-white py-8">
            <div class="container">
                <div class="row">
                    <div class="col-md-4 mb-4">
                        <h3>{{component.name}}</h3>
                        <p>智能网站生成器，为您的企业提供高效、专业的网站建设服务</p>
                    </div>
                    <div class="col-md-4 mb-4">
                        <h3>联系方式</h3>
                        <p><i class="fa fa-envelope mr-2"></i> contact@example.com</p>
                        <p><i class="fa fa-phone mr-2"></i> 400-123-4567</p>
                    </div>
                    <div class="col-md-4 mb-4">
                        <h3>关注我们</h3>
                        <a href="#" class="text-white mr-3"><i class="fa fa-weixin fa-2x"></i></a>
                        <a href="#" class="text-white mr-3"><i class="fa fa-weibo fa-2x"></i></a>
                        <a href="#" class="text-white"><i class="fa fa-linkedin fa-2x"></i></a>
                    </div>
                </div>
                <div class="text-center pt-4 border-t border-gray-700">
                    <p>&copy; ' . date('Y') . ' 智能网站生成器. 保留所有权利.</p>
                </div>
            </div>
        </footer>';
    }
    
    /**
     * 获取JavaScript代码
     */
    private function getJavaScriptCode()
    {
        $js = '<script>';
        $js .= '// 移动端菜单切换';
        $js .= 'document.addEventListener("DOMContentLoaded", function() {';
        $js .= '  const menuToggle = document.querySelector(".navbar-toggler");';
        $js .= '  const navbarCollapse = document.querySelector(".navbar-collapse");';
        $js .= '  ';
        $js .= '  if (menuToggle && navbarCollapse) {';
        $js .= '    menuToggle.addEventListener("click", function() {';
        $js .= '      navbarCollapse.classList.toggle("show");';
        $js .= '    });';
        $js .= '  }';
        $js .= '  ';
        $js .= '  // 平滑滚动';
        $js .= '  document.querySelectorAll(\'a[href^="#"]\').forEach(anchor => {';
        $js .= '    anchor.addEventListener(\'click\', function(e) {';
        $js .= '      e.preventDefault();';
        $js .= '      const targetId = this.getAttribute(\'href\');';
        $js .= '      if (targetId === \'#\') return;';
        $js .= '      const targetElement = document.querySelector(targetId);';
        $js .= '      if (targetElement) {';
        $js .= '        window.scrollTo({';
        $js .= '          top: targetElement.offsetTop - 80, // 考虑导航栏高度';
        $js .= '          behavior: \'smooth\'';
        $js .= '        });';
        $js .= '        // 关闭移动菜单（如果打开）';
        $js .= '        if (navbarCollapse && navbarCollapse.classList.contains(\'show\')) {';
        $js .= '          navbarCollapse.classList.remove(\'show\');';
        $js .= '        }';
        $js .= '      }';
        $js .= '    });';
        $js .= '  });';
        $js .= '});';
        $js .= '</script>';
        
        return $js;
    }
    
    /**
     * 保存生成的网站
     */
    private function saveGeneratedWebsite($html)
    {
        $dir = APP_PATH . '../../generated_sites/';
        
        // 确保目录存在
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        
        // 生成文件名
        $fileName = 'website_' . date('Ymd_His') . '_' . mt_rand(1000, 9999) . '.html';
        $filePath = $dir . $fileName;
        
        // 保存文件
        file_put_contents($filePath, $html);
        
        return $fileName;
    }
}